﻿using Furion.DataEncryption;
using Furion.FriendlyException;
using ZeroAdmin.Application.Entity;
using ZeroAdmin.Core;

namespace ZeroAdmin.Application;

/// <summary>
/// 系统操作服务
/// </summary>
public class SysOperateService : ISysOperateService
{
    /// <summary>
    /// 数据库操作：批量建表
    /// 执行效果：将数据库的表结构更新，表结构与代码一致。
    /// 要求需要建表的类的命名空间为：ZeroAdmin.Application.Entity    
    /// </summary>
    public void CreateTable()
    {
        try
        {
            Type[] types = typeof(DBEntityBase).Assembly.GetTypes().Where(it => it.FullName.Contains("ZeroAdmin.Application.Entity")).ToArray();
            SqlSugarHelper.CreateTable(types);
        }
        catch (Exception ex)
        {
            throw Oops.Bah($"数据库操作：批量建表失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 数据库操作：建立基础数据
    /// 执行要求：确保第一次建立基础数据
    /// </summary>
    /// <returns></returns>
    public async Task CreateBasicData()
    {
        try
        {
            List<SysConfig> configs = [];
            await SqlSugarHelper.InsertAsync(await GetNonexistenceList(configs));

            List<User> users = [new User { UserName = "系统管理员", PhoneNumber = "13800000000", Password = MD5Encryption.Encrypt("123456") }];
            await SqlSugarHelper.InsertAsync(await GetNonexistenceUserList(users));
        }
        catch (Exception ex)
        {
            throw Oops.Bah($"数据库操作：批量建表失败：{ex.Message}");
        }
    }

    /// <summary>
    /// 过滤存在系统配置
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    private async Task<IEnumerable<SysConfig>> GetNonexistenceList(List<SysConfig> input)
    {
        List<SysConfig> sysConfigs = [];
        foreach (SysConfig item in input)
        {
            if (!await SqlSugarHelper.Queryable<SysConfig>().AnyAsync(m => m.SysConfigName.Equals(item.SysConfigName) && m.Code.Equals(item.Code) && m.Value.Equals(item.Value)))
            {
                sysConfigs.Add(item);
            }
        }
        return sysConfigs;
    }

    /// <summary>
    /// 过滤存在的用户信息
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    private async Task<IEnumerable<User>> GetNonexistenceUserList(List<User> input)
    {
        List<User> users = [];
        foreach (User item in input)
        {
            if (!await SqlSugarHelper.Queryable<User>().AnyAsync(m => m.UserName.Equals(item.UserName) && m.PhoneNumber.Equals(item.PhoneNumber)))
            {
                users.Add(item);
            }
        }
        return users;
    }
}
